package com.xuerhua.yxt.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xuerhua.yxt.common.Configuration;
import com.xuerhua.yxt.common.Const;

public final class RequestUtil {
	
	/**
	 * 获取项目原路径
	 * @param request
	 * @return
	 */
	public static String getBasePath(HttpServletRequest request) {
		return request.getScheme() + "://"
				+ request.getServerName() + 
				(Configuration.getInstance().getEnv().equals("development") ? (":" + request.getServerPort()) : "")
				+ request.getContextPath();
	}
	
	public static String getOpenid(HttpServletRequest request) {
		if(Configuration.getInstance().getEnv().equals("development")) {
			return "oXDCCs3AjlFVcKWtJybY54gqP9hI";//oHNaQvxSMR9qAg3YmnNQ6acbNIgQ
		}
		return RequestUtil.getCookieValue(request, Const.OPENID_COOKIE);
	}
	
	public static String getCookieValue(HttpServletRequest request, String name) {  
	    Cookie cookies[] = request.getCookies();  
	    if (cookies != null) {  
	        for (Cookie cookie : cookies) {  
	            if (!cookie.getName().equals(name))  
	                continue;  
	            return cookie.getValue();  
	        }  
	    }  
	    return null;  
	}  
	
	public static void saveCookie(HttpServletResponse response, String name, String value, int maxAge){  
	    Cookie cookie = new Cookie(name, value);  
	    cookie.setMaxAge(maxAge);  
	    response.addCookie(cookie);
	}  
	
	public static String getIpAddr(HttpServletRequest request) {     
	      String ip = request.getHeader("x-forwarded-for");     
	      if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
	         ip = request.getHeader("Proxy-Client-IP");     
	     }     
	      if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
	         ip = request.getHeader("WL-Proxy-Client-IP");     
	      }     
	     if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
	          ip = request.getRemoteAddr();     
	     }     
	     return ip;     
	}
}
